<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入企业名称" class="search-main" @clear="clearSearch" v-model="params.name"/>
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="add">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="cardList" @expand-change="expandchange">
        <el-table-column type="expand">
          <template #default="scope"> 
            <el-table :data="scope.row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" >
                <template #default="scope">
                  {{ scope.row.startTime }}到{{ scope.row.endTime }}
                </template>
            </el-table-column>
              <el-table-column label="合同状态" prop="status" >
              <template #default="scope">
                <el-tag :type="formatType(scope.row.status)">{{ formatStatus(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text" :disabled="scope.row.status==3" @click="outRentAPI(scope.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status!=3" @click="delete(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" prop="id" :index="indexMethod"/>
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editItem(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.page"
      :page-sizes="[3, 6, 9]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total=total>
    </el-pagination>
    </div>
    <el-dialog
  :visible.sync="dialogVisible"
  width="30%"
  @open="openDialog"
  >
  <div class="form-container">
    <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
      <el-form-item label="租赁楼宇" prop="buildingId">
        <el-select v-model="rentForm.buildingId" placeholder="请选择">
          <el-option
            v-for="item in buildingList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租赁起止日期" prop="rentTime">
        <el-date-picker
          v-model="rentForm.rentTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId" >
          <el-upload
          ref="uploadRef"
            action="#"
            :http-request="uploadHandle"
            :limit="1"
            :before-upload="beforeValid"
            :on-exceed="onExceed"
            :on-remove="onRemove"
          >
            <el-button size="small" type="primary" plain>上传合同文件</el-button>
            <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      </div>

  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirm" >确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
  import { getParkListAPI,delParkAPI,addRentAPI,getRentListAPI,outRentAPI} from '@/api/park';
  import { uploadAPI } from '@/api/common';
  import {getBuildingRentListAPI} from '@/api/building'
  export default{
    data(){
      return{
        params:{
          name:'',
          contact:'',
          contactNumber:'',
          page:1,
          id:0,
          pageSize:3,

        },
          cardList:[],
          total:0,
          dialogVisible:false,
          buildingList:[],
          rentList:[],
          rentForm:{
            buildingId:null,
            startTime:null,
            endTime:null,
            contractUrl:null,
            contractId:null,
            rentTime:[],
            type:0,
            enterpriseId:null
          },
          rentRules:{
            buildingId:[
              {required:true,message:'楼宇不能为空',trigger:'change'}
            ],
            rentTime:[
              {required:true,message:'日期不能为空',trigger:'change'}
            ],
            contractId:[
              {required:true,message:'合同不能为空'}
            ]

          }
      }

    },
    created(){
      //创建方法
      this.getParkList()
      this.getbuildingList()
    },
    mounted(){
      this.getParkList()
    },
    methods:{
      //退租
      async outRent(id){
        await outRentAPI(id)
        this.getParkList()
      },
      formatType(status){
        const map={
          0:"success",
          1:"info",
          2:"warning",
          3:"danger"
        }
        return map[status]
      },
      formatStatus(status){
        const map={
          0:"待生效",
          1:"生效中",
          2:"已生效",
          3:"已退租"
        }
        return map[status]
      },
      //列表展开方法
     async expandchange(row,expandrow){
        // console.log(row)
        // console.log(expandrow)
        //判断展开和关闭：当展开时row里面的数据可以在expandrow里面找到
        //当关闭的时候row里面的数据是不能在expandrow里面找到的
        const isFind=expandrow.find(item=>item.id==row.id)
        if(isFind){
          console.log("展开")
          const res=await getRentListAPI(row.id)
          row.rentList=res.data
          
        }else{
          console.log("关闭")
        }
      },
      //移除合同列表的方法
      onRemove(){
        this.rentForm.contractId=""
        this.rentForm.contractUrl=""
        this.$refs.addForm.validate("contractId")
      },
      //合同大小及文件类型校验
      beforeValid(file){
        console.log(file)
        const whiteList=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/pdf"]
        const isLegal=whiteList.includes(file.type)
        const isSize=file.size/1024/1024<5
        if(!isLegal&&isSize){
          this.$message.error("文件不符合要求")
           return isLegal&&isSize
        }
      },
      //添加合同按钮方法
      addRent(id){
        this.dialogVisible=true
        this.rentForm.enterpriseId=id
      },
       confirm(){
        this.$refs.addForm.validate(async valid=>{
          if(!valid){
            return
          }
          const {buildingId,contractUrl,contractId,type,enterpriseId}=this.rentForm
          const reData={buildingId,contractUrl,startTime:this.rentForm.rentTime[0],
            endTime:this.rentForm.rentTime[1],contractId,type,enterpriseId}


             await addRentAPI(reData)
            this.dialogVisible=false
            //手动清除表单绑定的数据
           this.rentForm={
            buildingId:null,
            startTime:null,
            endTime:null,
            contractUrl:null,
            contractId:null,
            rentTime:[],
            type:0,
            enterpriseId:null
          }
          //清除表单数据及验证信息
          this.$refs.addForm.resetFields()
          //清楚已经上传文件的列表
          this.$refs.uploadRef.clearFiles()

        })
      },
      //文件超出个数时的方法
      onExceed(){
        this.$message.warning("最多只允许上传一个合同")
      },
      //上传合同方法
     async uploadHandle(res){
        var file=res.file
        //new 一个formdata对象
        var form=new FormData()
        //把file追加到form对象中
        form.append("file",file)
        form.append("type",2)
        //调用合同上传接口
      const _res=  await uploadAPI(form)
      console.log(_res)
      this.rentForm.contractId=_res.data.id
      this.rentForm.contractUrl=_res.data.url
      this.$refs.addForm.validateField("contractId")
      },
      //打开合同时方法
      openDialog(){
        this.getbuildingList()
      },
      //获取可租赁楼宇列表方法
      //调用方法
     async getbuildingList(){
        const res=await getBuildingRentListAPI()
        this.buildingList=res.data
      },

      clearSearch(){
        //查询到的数据，点击×之后，数据恢复到原来的样子
        this.getParkList()
      },
      add(){
        this.$router.push('/addpark')
      },

  delItem(id){
    this.$confirm('是否确定删除当前企业?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        await delParkAPI(id)

          this.$message({
            type: 'success',
            message: '企业已删除',
          });

        }).catch(() => {
          return
        });

  },
      search(){
        this.params.page=1
        this.getParkList()
      },
      indexMethod(index){
        return (this.params.page-1)*this.params.pageSize+index+1
      },
      handleSizeChange(val){
        // console.log(val)
        this.params.pageSize=val
        this.getParkList()
      },
      handleCurrentChange(val){
        // console.log(val)
        this.params.page=val
        this.getParkList()
      },
      async getParkList(){
        const res=await getParkListAPI(this.params)
        this.cardList=res.data.rows.map(item=>{
          return {
            ...item,
            rentList:[]
          }
          

        })
        
        this.total=res.data.total
        // console.log(res.rentList)
        // console.log(res.data)
       
      },
      editItem(id){
      // console.log(id)
      this.$router.push({
        path:'/addpark',
        query:{
        id:id
      }
    })
  },
    }

  }
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
